﻿using System;
using System.Text;

namespace SharpOSCAR.Base
{
    /// <summary>
    /// String data type
    /// </summary>
    public class String16 : ProtocolData, IString
    {
        private string _Value;
        /// <summary>
        /// Gets/sets the underlying string value
        /// </summary>
        public string Value
        {
            get { return _Value; }
            set { _Value = value; }
        }

        /// <summary>
        /// Returns a byte array representing the string
        /// </summary>
        /// <returns>Returns a byte array representing the string</returns>
        public override byte[] ToByteArray()
        {
            // Convert the string into a UTF8 byte array
            byte[] strBytes = Encoding.UTF8.GetBytes(_Value);
            // Create a buffer
            byte[] value = new byte[strBytes.Length + 2];
            // Get the bytes representing the string's length as an unsigned short
            byte[] lenBytes = BitConverter.GetBytes(Convert.ToUInt16(strBytes.Length));
            // Write the data into the buffer
            Buffer.BlockCopy(lenBytes, 0, value, 0, lenBytes.Length);
            if (BitConverter.IsLittleEndian)
            {
                byte temp = value[0];
                value[0] = value[1];
                value[1] = temp;
            }
            Buffer.BlockCopy(strBytes, 0, value, 2, strBytes.Length);

            return value;
        }

        /// <summary>
        /// Returns a byte array representing the string in "compressed" format
        /// </summary>
        /// <returns>Returns a byte array representing the string in "compressed" format</returns>
        public byte[] ToByteArrayCompressed()
        {
            // Convert the string to lowercase and remove all spaces
            string compressed = _Value.ToLower().Replace(" ", "");
            // Convert the compressed string into a UTF8 byte array
            byte[] strBytes = Encoding.UTF8.GetBytes(compressed);
            // Create a buffer
            byte[] value = new byte[strBytes.Length + 2];
            // Get the bytes representing the string's length as an unsigned short
            byte[] lenBytes = BitConverter.GetBytes(Convert.ToUInt16(strBytes.Length));
            // Write the data into the buffer
            Buffer.BlockCopy(lenBytes, 0, value, 0, lenBytes.Length);
            Buffer.BlockCopy(strBytes, 0, value, 2, strBytes.Length);

            return value;
        }
    }
}
